-- UITreeHouseMain
-- Created by cheny3 Feb/22/2016
-- 树屋主界面

require "game/ui/form/dungeon/special/UITreeHouseUpgrade"

UITreeHouseMain = class("UITreeHouseMain", function()
    return cc.Layer:create();
end);

function UITreeHouseMain.create(treeHouse)
    return UITreeHouseMain.new(treeHouse);
end

-- 构造函数
function UITreeHouseMain:ctor(treeHouse)
    self:setName("UITreeHouseMain");
    -- 复用幽灵船界面
    local node = cc.CSLoader:createNode("layout/ghost_ship/ShipMain.csb");
    self:addChild(node);
    self.node = node;

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    -- 记录树屋对象
    self.treeHouse = treeHouse;

    -- 注册事件处理回调函数
    self:registerEventCallback()

    -- 注册点击事件
    self:registerTouchEvent();

    -- 初始化窗口
    self:initForm();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 部分控件位置修正
function UITreeHouseMain:fixPos(desc1, desc2)
    -- desc1的Y轴位置
    local positionY = desc1:getPositionY();

    -- desc1文本控件的高度
    local labelHeight = getRealContentSize(desc1).height;

    -- 设置desc2的位置
    desc2:setPositionY(positionY - labelHeight - 6);
end

-- 适配
function UITreeHouseMain:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 播放升级特效
function UITreeHouseMain:playEffect(learnId)
    local effectNode;

    local skills = self.treeHouse:getSkills();

    local skillNum = 0;
    for _, info in pairs(skills) do
        -- 计算数量
        skillNum = skillNum + 1;
    end

    for i = 1, skillNum do
        local child = findChildByName(self.skillPanel, "skill" .. i);
        if learnId == child.skillId then
            effectNode = child;
            break;
        end
    end

    if effectNode then
        local levelLabel = findChildByName(effectNode, "text");
        self:scaleUpEffect(levelLabel);
        playEffect(effectNode, 1263, 0, -60, nil, 1.0);
        AudioM.playFx("workshop_upgrade1");
    end
end

-- 播放弹出效果
function UITreeHouseMain:scaleUpEffect(node)
    local scaleUp = cc.ScaleTo:create(0.3, 1.3);
    local scaleDown = cc.ScaleTo:create(0.15, 1);
    local delay = cc.DelayTime:create(0.01);
    node:setScale(1);
    node:runAction(cc.Sequence:create(delay, scaleUp, scaleDown));
end

-- 注册事件处理回调函数
function UITreeHouseMain:registerEventCallback()
    -- 关注技能升级技能事件
    EventMgr.register("UITreeHouseMain", event.UPGRADE_TREE_HOUSE_SKILL, function(args)
        self:redraw(true);
        -- 播放特效
        self:playEffect(args.skillId);
    end);

    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            cclog("UITreeHouseMain 界面析构清理");

            -- 移除所有事件关注
            EventMgr.removeAll("UITreeHouseMain");
            if UIDungeonMgr:getCurLevel() then
                UIDungeonMgr:getCurLevel():showMenu();
            end
        elseif eventType == "enter" then
            if UIDungeonMgr:getCurLevel() then
                UIDungeonMgr:getCurLevel():hideMenu();
            end
        end
    end);
end

-- 注册点击事件
function UITreeHouseMain:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");
            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UITreeHouseMain");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
end

-- 初始化窗口
function UITreeHouseMain:initForm()
    local skillPanel = findChildByName(self.node, "CT/skill_panel");
    self.skillPanel = skillPanel;

    local panelWidth  = skillPanel:getContentSize().width;
    local panelHeight = skillPanel:getContentSize().height;

    local posY = panelHeight/2;

    local iconWidth  = 94;
    local iconHeight = 94;

    -- 获取所有技能
    local skills = self.treeHouse:getSkills();
    local skillNum = 0;

    for _, info in pairs(skills) do
        -- 计算数量
        skillNum = skillNum + 1;
    end

    if skillNum == 0 then
        return;
    end

    -- 图标与图标直接的间距
    local gap = 25;
    local leftWGap = 20;

    for i = 1, skillNum do
        -- 暂时复用魔藤的技能图标
        local child = cc.CSLoader:createNode("layout/bine/SkillIcon.csb");
        local iconImg = findChildByName(child, "icon");
        child:setName("skill" .. i);
        local posX = iconWidth / 2 + (i - 1)*(iconWidth + gap) + leftWGap;
        child:setPosition(posX, posY);
        skillPanel:addChild(child);
        iconImg.oriScale = iconImg:getScale();

        -- 注册技能框点击事件
        local skillFrame = findChildByName(child, "frame");
        skillFrame:setTouchEnabled(true);
        local function onFrameClick(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                AudioM.playFx("button_click");
                local skillId = child.skillId;
                local skillLevel = self.treeHouse:getSkillLevel(skillId);
                -- 打开技能升级界面
                local uiForm = UITreeHouseUpgrade.create(skillId, skillLevel);
                UIMgr.getCurrentScene():addForm(uiForm);
            end
        end
        skillFrame:addTouchEventListener(onFrameClick);
    end
end

-- 重绘
function UITreeHouseMain:redraw(skillUp)
    -- 显示名称
    local classId = self.treeHouse.classId;
    local name = TreeHouseM.query(classId, "name");
    local titleLabel = findChildByName(self.node, "CT/common_bg/bg/title_label");
    titleLabel:setString(name);
    TextStyleM.setArtWordTitleStyle(titleLabel);

    -- 显示描述
    local descTitleLabel = findChildByName(self.node, "CT/desc_title");
    local descLabel = findChildByName(self.node, "CT/desc");
    local desc2Label = findChildByName(self.node, "CT/desc2");
    TextStyleM.setTextStyle(descTitleLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BEIGE, false, -1);

    local desc2Kerning = -1;
    if getLang() == "zh" or getLang() == "tw" then
        desc2Kerning = 0;
    end

    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, desc2Kerning);
    local desc = TreeHouseM.query(classId, "desc");
    descTitleLabel:setString(name);
    descLabel:setString(desc);

    local cycle = TreeHouseM.autoAttackRound(self.treeHouse);
    local attackDesc = string.format(TreeHouseM.query(classId, "skill_desc"), cycle);
    TextStyleM.setTextStyle(desc2Label, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_DARK_BROWN, nil, nil, nil, nil, nil, nil, nil, TextStyleM.getTextScale(attackDesc, 19 * 2));
    desc2Label:setString(attackDesc);

    self:fixPos(descLabel, desc2Label);

    -- 等级部分隐藏
    local levelNode = findChildByName(self.node, "CT/level_node");
    levelNode:setVisible(false);

    -- 显示模型
    self:redrawModel();

    -- 显示属性
    self:redrawAttrib();

    -- 显示技能
    self:redrawSkill(skillUp);
end

-- 显示图片
function UITreeHouseMain:redrawModel()
    local leftPart = findChildByName(self.node, "CT/left_part");

    local modelNode = findChildByName(leftPart, "model_node");
    modelNode:removeAllChildren();

    local icon = findChildByName(leftPart, "light");

    local iconName = TreeHouseM.query(self.treeHouse.classId, "icon");
    local iconPath = getLevelItemIconPath(iconName);
    icon:loadTexture(iconPath);

    -- 待机猴子
    self:monkeyEffect(icon);
 end

 -- 处理猴子光效
function UITreeHouseMain:monkeyEffect(node)
    local effectNode = node.monkeyNode;
    if not node.monkeyNode then
        -- 没有节点创建一个
        effectNode = cc.Node:create();
        node:addChild(effectNode);
        node.monkeyNode = effectNode;
    end
    effectNode:removeAllChildren();

    local treeHouse = ME.user.tree_house;
    if not treeHouse or not treeHouse:isActive() then
        -- 未激活，待机状态
        playEffect(effectNode, 1325, 80, 100);
        return;
    end

    -- 激活后的待机状态
    local preTreeHouseSubmit = ME.user.dbase:query("pre_tree_house_submit");
    local skillId = treeHouse:query("next_skill");
    if type(skillId) ~= "number" then
        skillId = TreeHouseM.querySkillByItemId(preTreeHouseSubmit[1], "skill_id");
    end

    if TreeHouseM.querySkill(skillId, "rule") == "up_power" then
        -- 紧箍，这个特殊一点
        playEffect(effectNode, 1324, 80, 100);
        return;
    end

    -- 一般的物品
    local classId = TreeHouseM.querySkill(skillId, "class_id");
    local iconPath = getTreeHouseItemIconPath(ItemM.query(classId, "icon"));

    local _, effect = playEffect(effectNode, 1322, 80, 100);
    local itemNode = findChildByName(effect, "throw_node/SpriteObject");
    itemNode:setTexture(iconPath);
end

-- 显示属性
function UITreeHouseMain:redrawAttrib()
    local valueLabel, nameLabel;
    local rightPart = findChildByName(self.node, "CT/common_bg/right_part");

    -- 只有攻击
    local attackRange = self.treeHouse:getAttackRange(true);

    -- 攻击
    nameLabel = findChildByName(rightPart, "attack_node/name");
    valueLabel= findChildByName(rightPart, "attack_node/value");
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    TextStyleM.setTextStyle(valueLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    nameLabel:setString(getLocStr("attack"));
    valueLabel:setString(string.format(getLocStr("range_desc"), attackRange[1], attackRange[2]));

    -- 生命
    local nameLabel= findChildByName(rightPart, "hp_node/name");
    local valueLabel= findChildByName(rightPart, "hp_node/value");
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    TextStyleM.setTextStyle(valueLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    nameLabel:setString(getLocStr("hp"));
    valueLabel:setString("--");

    -- 魔力
    local nameLabel= findChildByName(rightPart, "dodge_node/name");
    local valueLabel= findChildByName(rightPart, "dodge_node/value");
    local iconImg = findChildByName(rightPart, "dodge_node/icon");
    iconImg:loadTexture(getSmallAttribIconPath("magic"));
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    TextStyleM.setTextStyle(valueLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    nameLabel:setString(getLocStr("magic"));
    valueLabel:setString("--");

    -- 魔法
    local nameLabel= findChildByName(rightPart, "accuracy_node/name");
    local valueLabel= findChildByName(rightPart, "accuracy_node/value");
    local iconImg = findChildByName(rightPart, "accuracy_node/icon");
    iconImg:loadTexture(getSmallAttribIconPath("mp"));
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    TextStyleM.setTextStyle(valueLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
    nameLabel:setString(getLocStr("mp"));
    valueLabel:setString("--");
end

-- 显示技能
function UITreeHouseMain:redrawSkill(skillUp)
    -- 获取所有技能
    local skills = self.treeHouse:getSkills();
    local skillNum = 0;
    local i = 1;

    for _, info in pairs(skills) do
        -- 计算数量
        skillNum = skillNum + 1;
    end

    if skillNum == 0 then
        return;
    end

    local skillsList = {};

    -- 按照玩家身上字段排序
    local preTreeHouseSubmit = ME.user.dbase:query("pre_tree_house_submit");
    for _, itemId in pairs(preTreeHouseSubmit) do
        local skillId = TreeHouseM.querySkillByItemId(itemId, "skill_id");
        table.insert(skillsList, {skillId, tonumber(skills[skillId])});
    end

    for _, info in pairs(skillsList) do
        local child    = findChildByName(self.skillPanel, "skill" .. i);
        local iconImg  = findChildByName(child, "icon");
        local starNode = findChildByName(child, "star_node");
        local frame    = findChildByName(child, "frame");
        local levelLabel = findChildByName(child, "text");

        local skillId = info[1];
        local skillInfo = TreeHouseM.querySkill(skillId);

        if not skillInfo then
            error(string.format("获取不到技能(%d)配置", skillId));
        end

        local iconName = ItemM.query(skillInfo["class_id"], "icon");
        local iconPath = getItemIconPath(iconName);

        -- 绘制技能图标
        iconImg:loadTexture(iconPath);

        -- 获取技能等级
        local level = self.treeHouse:getSkillLevel(skillId);
        local maxLevel = skillInfo["max_level"];
        child.skillId = skillId;

        -- 有物品并且没有满级
        iconImg:stopAllActions();
        if iconImg.oriScale then
            iconImg:setScale(iconImg.oriScale);
        end
        if ItemM.getAmount(ME.user, skillInfo["class_id"]) > 0
            and ((type(maxLevel) == "number" and maxLevel > level)
                or type(maxLevel) ~= "number") then
            playBubbleAnima(iconImg, false);
        end

        starNode:setVisible(false);
        TextStyleM.setTextStyle(levelLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_LIGHT_BLUE, true, -2);
        levelLabel:setString(string.format(getLocStr("talent_level_format"), tostring(level)));
        levelLabel:setVisible(true);
        i = i + 1;
    end
end






